﻿using Blogger.UI.Models;
using Microsoft.WindowsAzure.Storage.Blob;
using POC.Azure.Storage;
using POC.Reports;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;

namespace Blogger.UI.Controllers
{
    public class UIController : Controller
    {
        public UIController()
        {
            if (WebRequest.DefaultWebProxy.Credentials == null)
            {
                WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultCredentials;
            }
        }

        protected string TextType = "text/plain";
        protected string clientHeaderFile = "X-File-Name";
        AzureAccount account = AzureConfig.AzureAccount;
        protected HttpResponseMessage GetResponse(object ob, string mimeType)
        {
            Response.ContentType = mimeType;// "text/plain";
            var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            var result = new { name = ob.ToString() };
            Response.Write(serializer.Serialize(result));
            Response.StatusCode = 200;
            return new HttpResponseMessage(HttpStatusCode.OK);
        }
        protected string EncodeFile(string fileName)
        {
            return Convert.ToBase64String(System.IO.File.ReadAllBytes(fileName));
        }
        protected void UploadPartialFile(string fileName, HttpRequestBase request, List<ViewDataUploadFilesResult> statuses)
        {
            if (request.Files.Count != 1) throw new HttpRequestValidationException("Attempt to upload chunked file containing more than one fragment per request");
            var file = request.Files[0];
            var inputStream = file.InputStream;

            var fullName = Path.Combine(StorageRoot, Path.GetFileName(fileName));

            using (var fs = new FileStream(fullName, FileMode.Append, FileAccess.Write))
            {
                var buffer = new byte[1024];

                var l = inputStream.Read(buffer, 0, 1024);
                while (l > 0)
                {
                    fs.Write(buffer, 0, l);
                    l = inputStream.Read(buffer, 0, 1024);
                }
                fs.Flush();
                fs.Close();
            }
            statuses.Add(new ViewDataUploadFilesResult()
            {
                name = fileName,
                size = file.ContentLength,
                type = file.ContentType,
                url = "/Upload/Download/" + fileName,
                delete_url = "/Upload/Delete/" + fileName,
                thumbnail_url = @"data:image/png;base64," + EncodeFile(fullName),
                delete_type = "GET",
            });
        }
        protected string StorageRoot
        {
            get { return @"C:\Lab\Azure\POC\BlogAPI\Files"; }
        }
        protected void UploadWholeFile(HttpRequestBase request, List<ViewDataUploadFilesResult> statuses)
        {
            for (int i = 0; i < request.Files.Count; i++)
            {
                var file = request.Files[i];
                if (file.ContentLength > 100)
                {
                    var fullPath = Path.Combine(StorageRoot, Path.GetFileName(file.FileName));

                    file.SaveAs(fullPath);
                    statuses.Add(new ViewDataUploadFilesResult()
                    {
                        name = file.FileName,
                        size = file.ContentLength,
                        type = file.ContentType,
                        url = "/Upload/Download/" + file.FileName,
                        delete_url = "/Upload/Delete/" + file.FileName,
                        thumbnail_url = @"data:image/png;base64," + EncodeFile(fullPath),
                        delete_type = "GET",
                    });
                }
                else
                {
                    statuses.Add(new ViewDataUploadFilesResult()
                    {
                        name = string.Empty,
                        size = file.ContentLength,
                        type = string.Empty,
                        url = string.Empty,
                        delete_url = string.Empty,
                        thumbnail_url = string.Empty,
                        delete_type = "GET",
                    });
                }


            }
        }
        /// <summary>
        /// //////////////////////////////////////////////////
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="request"></param>
        /// <param name="statuses"></param>
        protected void WritePartialBlob(string fileName, HttpRequestBase request, List<ViewDataUploadFilesResult> statuses)
        {
            if (request.Files.Count != 1) throw new HttpRequestValidationException("Attempt to upload chunked file containing more than one fragment per request");
            var file = request.Files[0];
            var inputStream = file.InputStream;
            var safeFileName = Regex.Replace(Path.GetFileName(fileName), "[^a-zA-Z0-9./]+", "", RegexOptions.Compiled);
            var fullName = Path.Combine(StorageRoot, Path.GetFileName(fileName));


            CloudBlobClient blobClient = account.CloudAccount.CreateCloudBlobClient();
            var root = blobClient.GetContainerReference("root");
            blobClient.SingleBlobUploadThresholdInBytes = 1024;
            root.CreateIfNotExists();
            var blob = root.GetBlockBlobReference(safeFileName);
            string mimeType = FileLoaderExtn.GetMimeType(file.FileName);
            blob.Properties.ContentType = mimeType;
            blob.UploadFromStream(inputStream);

            /*
            using (var fs = new FileStream(fullName, FileMode.Append, FileAccess.Write))
            {
                var buffer = new byte[1024];

                var l = inputStream.Read(buffer, 0, 1024);
                while (l > 0)
                {
                    fs.Write(buffer, 0, l);
                    l = inputStream.Read(buffer, 0, 1024);
                }
                fs.Flush();
                fs.Close();
            }
             * */
            statuses.Add(new ViewDataUploadFilesResult()
            {
                name = fileName,
                size = file.ContentLength,
                type = file.ContentType,
                url = "/Upload/Download/" + fileName,
                delete_url = "/Upload/Delete/" + fileName,
                thumbnail_url = blob.Uri.ToString(),
                delete_type = "GET",
            });
        }
        protected void WriteBlob(HttpRequestBase request, List<ViewDataUploadFilesResult> statuses)
        {
            for (int i = 0; i < request.Files.Count; i++)
            {
                var file = request.Files[i];
                if (file.ContentLength > 100)
                {
                    var fullName = Path.Combine(StorageRoot, Path.GetFileName(file.FileName));
                    var inputStream = file.InputStream;
                    var safeFileName = Regex.Replace(Path.GetFileName(file.FileName), "[^a-zA-Z0-9./]+", "", RegexOptions.Compiled);

                    CloudBlobClient blobClient = account.CloudAccount.CreateCloudBlobClient();
                    var root = blobClient.GetContainerReference("root");
                    //blobClient.SingleBlobUploadThresholdInBytes = 1024;
                    //root.CreateIfNotExists();

                    var blob = root.GetBlockBlobReference(safeFileName);
                    string mimeType = FileLoaderExtn.GetMimeType(file.FileName);
                    blob.Properties.ContentType = mimeType;
                    blob.UploadFromStream(inputStream);

                    statuses.Add(new ViewDataUploadFilesResult()
                    {
                        name = file.FileName,
                        size = file.ContentLength,
                        type = file.ContentType,
                        url = "/Upload/Download/" + file.FileName,
                        delete_url = "/Upload/Delete/" + file.FileName,
                        thumbnail_url = blob.Uri.ToString(),
                        delete_type = "GET",
                    });
                }
                else
                {
                    statuses.Add(new ViewDataUploadFilesResult()
                    {
                        name = string.Empty,
                        size = file.ContentLength,
                        type = string.Empty,
                        url = string.Empty,
                        delete_url = string.Empty,
                        thumbnail_url = string.Empty,
                        delete_type = "GET",
                    });
                }


            }
        }

        protected IEnumerable GetBloblist(string container)
        {
            CloudBlobClient blobClient = account.CloudAccount.CreateCloudBlobClient();
            var root = blobClient.GetContainerReference(container);

            var bloblist = root.ListBlobs().Cast<ICloudBlob>().ToList();
            var kps = (from b in bloblist select new { }).ToList();
            return bloblist;
        }
        protected IEnumerable DeleteBloblist(string container, string allUrls)
        {

            CloudBlobClient blobClient = account.CloudAccount.CreateCloudBlobClient();
            var root = blobClient.GetContainerReference(container);
            string[] urls = allUrls.Split(";".ToCharArray());
            foreach (string url in urls)
            {
                if (!string.IsNullOrEmpty(url))
                {
                    try
                    {
                        Uri uri = new Uri(url);
                        var blob = blobClient.GetBlobReferenceFromServer(uri);
                        blob.DeleteIfExists();
                    }
                    catch (Exception cx)
                    {
                    }
                }
            }
            var bloblist = root.ListBlobs().Cast<ICloudBlob>().ToList();
            var kps = (from b in bloblist select new { }).ToList();
            return bloblist;
        }

        public int GetIntCounter()
        {
           int aVal =  Guid.NewGuid().GetHashCode();
           if (aVal < 0) aVal = aVal * (-1);
           return aVal;
        }
        public string GetNewID()
        {
            Random rand = new Random();
           int x = rand.Next(99999, 999999);
           return x.ToString();
        }

    }
}
